﻿using System.Collections.Generic;
using System.Linq;
using KTOP.Core.Domain.Matrix;

namespace KTOP.Homeworks.Hw4.Logics.DijkstraRoutes
{
    class DijkstraRouteBuilder
    {
        public static List<RouteLabel[]> FindRoutes(CMatrix cMatrix)
        {
            var routeMap = new List<RouteLabel[]>();

            var xLables = Enumerable.Range(0, cMatrix.Size)
                .Select(_ => RouteLabel.Infinite)
                .ToArray();

            xLables[0] = RouteLabel.Constantly(0);
            var lastConst = 0;

            var rows = cMatrix.Matrix.Select(r => r.ToArray()).ToArray();
            var rowId = 0;

            while (xLables.Any(xl => !xl.IsConstant))
            {
                routeMap.Add(xLables.Select(r => r.Copy()).ToArray());
                for (var id = 0; id < xLables.Length; id++)
                {
                    if (rows[rowId][id] != 0)
                        if (!xLables[id].IsConstant)
                        {
                            if (xLables[id] > rows[rowId][id] + lastConst)
                                xLables[id] = RouteLabel.Value(rows[rowId][id] + lastConst);

                        }
                }

                var nextConst = xLables
                        .OrderBy(xl => xl.RouteValue)
                        .First(xl => !xl.IsInfinite && !xl.IsConstant);

                nextConst.IsConstant = true;
                lastConst = nextConst.RouteValue;

                rowId++;
            }

            routeMap.Add(xLables.Select(r => r.Copy()).ToArray());
            return routeMap;
        }
    }
}
